package com.sixth.volunteerservicesystem.Controller.news;

import com.sixth.volunteerservicesystem.Service.NewsService;
import com.sixth.volunteerservicesystem.domain.News;
import com.sixth.volunteerservicesystem.domain.Theory;
import com.sixth.volunteerservicesystem.domain.Video;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

@Controller
public class NewsBack {
    @Autowired
    NewsService newsService;

    @RequestMapping("/addnews")
    public String addnews(News news){
        return "news/addnews";
    }

    @GetMapping("/newsback")
    public String newsback(Model model){
        List<News> news = newsService.list();
        model.addAttribute("news",news);
        return "news/newsback";
    }




    @PostMapping("/savenews")
    public String uploadvideo(News news, HttpServletRequest request) throws IOException {
        FileOutputStream fos;
        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest)request;
        MultipartFile file = multipartHttpServletRequest.getFile("file");
        InputStream is = file.getInputStream();
        String path= ResourceUtils.getURL("src/main/resources").getPath()+"/static/upload/";
        fos = new FileOutputStream(new File(path+file.getOriginalFilename()));
        byte[] buffer = new byte[1024];
        int len;
        while((len = is.read(buffer)) != -1){
            fos.write(buffer, 0, len);
        }
        String s="/upload/"+file.getOriginalFilename();
        news.setImg(s);
        newsService.sava(news);

        return  "redirect:/newsback";
    }

    @GetMapping("/newsdetailback/{id}")
    public String theorydetailback(@PathVariable("id")int id, Model model) {
        News news = newsService.Getone(id);
        model.addAttribute("news",news);
        return "news/newsdetailback";
    }
    @GetMapping("/deletenews/{id}")
    public String delete(@PathVariable("id")int id, Model model) {
        newsService.delete(id);
        return "redirect:/newsback";
    }

}
